from network_form.utils_network import read_data,load_all_graphs,form_feature,weight_edge,count_topics
import numpy as np

data_path = "../data_process/All_Unpack/"
graphs_path = "../network_form/all_graphs.pkl"



def get_sim(topic1,topic2):
    new_member_topic=topic1.copy()
    new_member_topic.extend(topic2)
    event_topics_dict=list(set(new_member_topic))
    feature_dim=len(event_topics_dict)

    feature1=form_feature(topic1, feature_dim, event_topics_dict)
    feature2=form_feature(topic2, feature_dim, event_topics_dict)
    sim=weight_edge(feature1,feature2)
    return sim

# 这个解决的是一个member开始事件和最近的第k个事件的相似度的分段，和sixth.py很像,但是这里不是求最新事件和最初事件的相似度,而是
# 把最初的事件换成了离现在事件跨度为k的事件
if __name__ == "__main__":
    event_list, topic_dict, member_list, group_list = read_data(data_path, rebuild=False)
    # all_graphs = load_all_graphs(graphs_path)
    group_topics={}
    for item in group_list:
        group_topics[item['id']]=item['topics']

    event_topics={}
    for item in event_list:
        group_id=item['group_id']
        event_topics[item['id']]=group_topics[group_id]

    member_topics={}
    for item in member_list:
        member_topics[item['id']]=item['topics']
        if item['id']=='10393986':
            print('id')


    member_event={}
    for event in event_list:
        members=list(event['member and response'].keys())
        start_time=event['start_time']
        event_id=event['id']
        for id in members:
            if id in member_event:
                if len(member_event[id])>=1:
                    time1=member_event[id][0][0]
                    member_event[id].append((start_time,event_id))
                    if start_time<time1:
                        member_event[id][0],member_event[id][-1]=member_event[id][-1],member_event[id][0]
            else:
                member_event[id]=[(start_time,event_id)]

    k=5
    len_x=10
    width_x=1/len_x
    sum_cos=np.zeros((len_x,))
    for id,events in member_event.items():
        if len(events)<2:
            continue
        if id not in member_topics:
            continue
        member_topic=member_topics[id]
        events=sorted(events,reverse=True)
        range_k=k if len(events)>=k+1 else len(events)-1

        event_id1=events[0][1]
        event_id2=events[range_k][1]
        topic1=event_topics[event_id1]
        topic2=event_topics[event_id2]

        new_member_topic=topic1.copy()
        new_member_topic.extend(topic2)
        event_topics_dict=list(set(new_member_topic))
        feature_dim=len(event_topics_dict)

        feature1=form_feature(topic1, feature_dim, event_topics_dict)
        feature2=form_feature(topic2, feature_dim, event_topics_dict)
        sim=weight_edge(feature1,feature2)
        i=int(sim/width_x)
        if i>=len_x:
            i=len_x-1
        sum_cos[i]+=1


    print(sum_cos/np.sum(sum_cos))
    print(sum_cos)







